package archer.back.controllers

import archer.back.models.SimpleNodeInfo
import play.api.mvc.ControllerComponents
import utils._
import io.circe.syntax._
import io.circe.generic.auto._
import cats.implicits._
import models.TableData
import play.api.libs.circe.Circe
import play.api.libs.ws.WSClient

import scala.util.Try

class NodeInfoController(
  controllerComponents: ControllerComponents,
  wsClient: WSClient,
  nodeInfoService: NodeInfoService)
  extends BackController(controllerComponents)
  with Circe
  with ArcherHelper {

  implicit val ec = defaultExecutionContext

  def fetch(id: Int) = Action.async { implicit request =>
    nodeInfoService.fetch(treeNodeId = id).map {
      case Some(model) =>
        Ok(TableData(data = model, count = Option(1)).asJson)
      case _ =>
        NotFound(TableData.msg("找不到对应 Node 的信息").asJson)
    }
  }

  def testSelector(
    url: String,
    timeSelector: String,
    titleSelector: String,
    timeFormatter: String) = Action.async { implicit request =>
    nodeInfoService
      .testSelector(
        url = url,
        timeSelector = timeSelector,
        titleSelector = titleSelector,
        timeFormatter = timeFormatter)
      .map {
        case s if s.data.isDefined =>
          Ok(s.asJson)
        case s =>
          InternalServerError(s.asJson)
      }
  }

  def create = Action.async(circe.json[SimpleNodeInfo]) { implicit request =>
    nodeInfoService
      .create(request.body)
      .map {
        case s if s === true =>
          Ok(TableData.msg("新增监控信息成功").asJson)
        case s =>
          InternalServerError(TableData.msg("新增监控信息失败").asJson)
      }
  }

  def update = Action.async(circe.json[SimpleNodeInfo]) { implicit request =>
    nodeInfoService
      .update(request.body)
      .map {
        case s if s === true =>
          Ok(TableData.msg("修改监控信息成功").asJson)
        case s =>
          InternalServerError(TableData.msg("修改监控信息失败").asJson)
      }
  }

}
